﻿#pragma execution_character_set("utf-8")

#include "SoftwareTrayIcon.h"

#include <QDebug>
#include <QApplication>

namespace GeneralUI {

	SoftwareTrayIcon::SoftwareTrayIcon(QObject *parent)
		: QObject(parent)
		, m_pMainWidget(nullptr)
		, m_bExitDirect(true)
		, m_pMenu(new QMenu)
	{
		m_pSystemTrayIcon = new QSystemTrayIcon(this);
		connect(m_pSystemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(slotIconIsActived(QSystemTrayIcon::ActivationReason)));
	}

	SoftwareTrayIcon::~SoftwareTrayIcon()
	{
		if (m_pSystemTrayIcon != nullptr)
		{
			delete m_pSystemTrayIcon;
			m_pSystemTrayIcon = nullptr;
		}
	}

	void SoftwareTrayIcon::setMainWidget(QWidget *mainWidget)
	{
		this->m_pMainWidget = mainWidget;
		m_pMenu->addAction("显示主界面", this, SLOT(slotShowMainWidget()));
		m_pMenu->addAction("最小化", this, SLOT(slotShowMainWidget()));
		m_pMenu->addAction("关于软件", this, SLOT(slotShowMainWidget()));

		if (m_bExitDirect) 
		{
			m_pMenu->addAction("退出", this, SLOT(slotCloseMainWidget()));
		}
		else
		{
			m_pMenu->addAction("退出", this, SIGNAL(slotTrayIconExit()));
		}

		m_pSystemTrayIcon->setContextMenu(m_pMenu);
	}

	void SoftwareTrayIcon::setIcon(const QString &strIcon)
	{
		m_pSystemTrayIcon->setIcon(QIcon(strIcon));
	}

	void SoftwareTrayIcon::setToolTip(const QString &tip)
	{
		m_pSystemTrayIcon->setToolTip(tip);
	}

	void SoftwareTrayIcon::setVisible(bool visible)
	{
		m_pSystemTrayIcon->setVisible(visible);
	}

	bool SoftwareTrayIcon::getVisible() const
	{
		return m_pSystemTrayIcon->isVisible();
	}

	void SoftwareTrayIcon::showMessage(const QString &title, const QString &msg, QSystemTrayIcon::MessageIcon icon, int msecs)
	{
		m_pSystemTrayIcon->showMessage(title, msg, icon, msecs);
	}

	void SoftwareTrayIcon::setExitDirect(bool exitDirect)
	{
		if (this->m_bExitDirect != exitDirect)
		{
			this->m_bExitDirect = exitDirect;
		}
	}

	void SoftwareTrayIcon::slotShowMainWidget()
	{
		if (m_pMainWidget) 
		{
			m_pMainWidget->showNormal();
			m_pMainWidget->activateWindow();
		}
	}

	void SoftwareTrayIcon::slotCloseMainWidget()
	{
		m_pSystemTrayIcon->hide();
		m_pSystemTrayIcon->deleteLater();
		qApp->exit();
	}

	void SoftwareTrayIcon::slotIconIsActived(QSystemTrayIcon::ActivationReason reason)
	{
		switch (reason) {
		case QSystemTrayIcon::Trigger:
		case QSystemTrayIcon::DoubleClick:
		{
			this->slotShowMainWidget();
			break;
		}
		default:
			break;
		}
	}

}//namespace OfUI